﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;

namespace TestControls {
  public abstract class ObjectBase : INotifyPropertyChanged {

    private bool hasChanged, isNew;

    #region - Properties -

    /// <summary>
    /// Gets or sets a value indicating whether this instance is new.
    /// </summary>
    /// <value>
    ///   <c>true</c> if this instance is new; otherwise, <c>false</c>.
    /// </value>
    public bool IsNew {
      get { return isNew; }
      set { isNew = value; }
    }

    /// <summary>
    /// Gets or sets a value indicating whether this instance has changed.
    /// </summary>
    /// <value>
    /// 	<c>true</c> if this instance has changed; otherwise, <c>false</c>.
    /// </value>
    public bool HasChanged {
      get { return hasChanged; }
      set { hasChanged = value; }
    }

    #endregion

    #region methods

    /// <summary>
    /// Marks the object as clean.
    /// </summary>
    public virtual void MarkClean( ) {
      this.HasChanged = false;
    }

    /// <summary>
    /// Marks the object as new.
    /// </summary>
    public virtual void MarkNew( ) {
      this.IsNew = true;
    }

    /// <summary>
    /// Sets the propertyfield value.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="oldValue">The old value.</param>
    /// <param name="newValue">The new value.</param>
    /// <param name="propertyName">Name of the property.</param>
    /// <returns></returns>
    protected bool SetField<T>( ref T oldValue, T newValue, string propertyName ) {
      if ( EqualityComparer<T>.Default.Equals( oldValue, newValue ) ) {
        //hasChanged = hasChanged ? hasChanged : false;
        return false;
      }

      oldValue = newValue;
      hasChanged = hasChanged ? hasChanged : true;
      OnPropertyChanged( propertyName );
      return true;
    }

    /// <summary>
    /// Called when [property changed].
    /// </summary>
    /// <param name="propertyName">Name of the property.</param>
    protected virtual void OnPropertyChanged( string propertyName ) {
      PropertyChangedEventHandler handler = PropertyChanged;
      if ( handler != null ) handler( this, new PropertyChangedEventArgs( propertyName ) );
    }

    #endregion

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    #endregion
  }
}
